﻿using CraftParameterConfig.Domain.Interfaces;
using CraftParameterConfig.Infrastructure.Common;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CraftParameterConfig.Infrastructure.Data
{
    class UnitOfWork : IUnitOfWork
    {
        DbConnection dbConnection;
        public DbTransaction BeginTransaction()
        {
            if (GlobalObjects.DbTransaction == null)
            {
                dbConnection = GlobalObjects.DbContext.GetDbConnection();
                dbConnection.Open();
                GlobalObjects.DbTransaction = dbConnection.BeginTransaction();
            }
            GlobalObjects.TransactionNumber = 1;
            return GlobalObjects.DbTransaction;
        }

        public void SaveChange()
        {
            if (GlobalObjects.DbTransaction == null)
            {
                throw new NullReferenceException("全局事务对象为空,请注意!");
            }
            else
            {
                if (GlobalObjects.TransactionNumber == 1)
                {
                    try
                    {
                        GlobalObjects.DbTransaction.Commit();
                    }
                    catch (Exception)
                    {
                        GlobalObjects.DbTransaction.Rollback();
                        throw;
                    }
                    finally
                    {
                        dbConnection.Close();
                        GlobalObjects.DbTransaction = null;
                    }
                }
                GlobalObjects.TransactionNumber = -1;
            }
        }
    }
}
